package com.uduemc.biso.node.web.api.controller;

import java.io.IOException;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModel;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModelAction;
import com.uduemc.biso.node.core.operate.entities.OperateLog;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.dto.RequestActionPublishSave;
import com.uduemc.biso.node.web.api.dto.RequestPublishData;
import com.uduemc.biso.node.web.api.service.PublishService;
import com.uduemc.biso.node.web.service.OperateLoggerService;
import com.uduemc.biso.node.web.utils.IpUtil;

@RestController
@RequestMapping("/api/action")
public class ActionController {

	private final static Logger logger = LoggerFactory.getLogger(ActionController.class);

	@Autowired
	ObjectMapper objectMapper;

	@Autowired
	RequestHolder requestHolder;

	@Autowired
	PublishService publishServiceImpl;

	@Autowired
	OperateLoggerService operateLoggerServiceImpl;

	@PostMapping("/publish/save")
	public JsonResult save(@Valid @RequestBody RequestPublishData requestPublishData, BindingResult errors)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (errors.hasErrors()) {
			for (FieldError fieldError : errors.getFieldErrors()) {
				String defaultMessage = fieldError.getDefaultMessage();
				String field = fieldError.getField();
				logger.info("field: " + field + "defaultMessage: " + defaultMessage);
				return JsonResult.messageError(defaultMessage);
			}
		}

		String dataJson = null;
		try {
			dataJson = CryptoJava.de(requestPublishData.getData());
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (StringUtils.isEmpty(dataJson)) {
			return JsonResult.messageError("未能解析请求的body体！");
		}

		logger.info("dataBodyJson: " + dataJson);
		RequestActionPublishSave publishSave = null;
		try {
			publishSave = objectMapper.readValue(dataJson, RequestActionPublishSave.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.info("publishSave: " + publishSave);

		if (publishSave == null) {
			return JsonResult.messageError("未能解析请求的数据！");
		}

		long hostId = publishSave.getDataBody().getHostId();

		long siteId = publishSave.getDataBody().getSiteId();

		if (requestHolder.getHost().getId().longValue() != hostId) {
			return JsonResult.messageError("验证主机ID不过！");
		}

		if (requestHolder.getCurrentSite().getId().longValue() != siteId) {
			return JsonResult.messageError("验证站点ID不过！");
		}

		boolean save = publishServiceImpl.save(publishSave.getDataBody(), publishSave.getOperateLog());

		if (save) {
			OperateLog log = new OperateLog();
			log.setHostId(requestHolder.getHost().getId()).setSiteId(requestHolder.getCurrentSite().getId())
					.setLanguageId(requestHolder.getCurrentSite().getLanguageId());
			log.setUserId(requestHolder.getUserId()).setUserType(requestHolder.getUsertype()).setUsername(requestHolder.getUsername());
			String modelName = OperateLoggerStaticModel.findModelName(ActionController.class.getName());
			String modelAction = OperateLoggerStaticModel.findModelAction(ActionController.class.getName(), OperateLoggerStaticModelAction.PUBLISH);
			log.setModelName(modelName).setModelAction(modelAction).setContent("系统后台设计区域，点击发布！");
			log.setParam(dataJson).setOperateItem(String.valueOf(publishSave.getDataBody().getPageId())).setReturnValue("");
			log.setStatus((short) 1).setIpaddress(IpUtil.getIpAddr(requestHolder.getCurrentRequest()));
			operateLoggerServiceImpl.insert(log);

			return JsonResult.messageSuccess("发布成功！");
		} else {
			return JsonResult.messageError("保存错误，请联系系统管理员！");
		}

	}

	@PostMapping("/publish/operate-logger-static-model")
	public JsonResult operateLoggerStaticModel() {
		OperateLoggerStaticModel findOperateLoggerStaticModel = OperateLoggerStaticModel.findOperateLoggerStaticModel(ActionController.class.getName());
		return JsonResult.ok(findOperateLoggerStaticModel);
	}
}
